const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');

// 添加调试日志
console.log('Plan routes are being registered');

// 获取计划列表
router.get('/plans', async (req, res) => {
  console.log('GET /plans request received');
  try {
    const { date } = req.query;
    let sql = 'SELECT * FROM plans';
    const params = [];

    if (date) {
      sql += ' WHERE date = ?';
      params.push(date);
    }

    sql += ' ORDER BY date ASC, time ASC';
    
    console.log('Executing SQL:', sql, 'with params:', params);
    const [plans] = await pool.query(sql, params);
    console.log('Query result:', plans);
    
    res.json({ success: true, data: plans });
  } catch (error) {
    console.error('获取计划列表失败:', error);
    res.status(500).json({ success: false, message: '获取计划列表失败' });
  }
});

// 创建计划
router.post('/plans', async (req, res) => {
  try {
    const { name, date, timeType, time } = req.body;
    
    if (!name || !date || !timeType || !time) {
      return res.status(400).json({ success: false, message: '请填写完整信息' });
    }

    const sql = 'INSERT INTO plans (name, date, time_type, time) VALUES (?, ?, ?, ?)';
    const [result] = await pool.query(sql, [name, date, timeType, time]);

    res.json({ 
      success: true, 
      data: { 
        id: result.insertId,
        name,
        date,
        timeType,
        time,
        notified: false
      } 
    });
  } catch (error) {
    console.error('创建计划失败:', error);
    res.status(500).json({ success: false, message: '创建计划失败' });
  }
});

// 更新计划
router.put('/plans/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, date, timeType, time } = req.body;

    if (!name || !date || !timeType || !time) {
      return res.status(400).json({ success: false, message: '请填写完整信息' });
    }

    const sql = 'UPDATE plans SET name = ?, date = ?, time_type = ?, time = ? WHERE id = ?';
    await pool.query(sql, [name, date, timeType, time, id]);

    res.json({ success: true });
  } catch (error) {
    console.error('更新计划失败:', error);
    res.status(500).json({ success: false, message: '更新计划失败' });
  }
});

// 删除计划
router.delete('/plans/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const sql = 'DELETE FROM plans WHERE id = ?';
    await pool.query(sql, [id]);
    res.json({ success: true });
  } catch (error) {
    console.error('删除计划失败:', error);
    res.status(500).json({ success: false, message: '删除计划失败' });
  }
});

// 更新计划提醒状态
router.put('/plans/:id/notify', async (req, res) => {
  try {
    const { id } = req.params;
    const sql = 'UPDATE plans SET notified = 1 WHERE id = ?';
    await pool.query(sql, [id]);
    res.json({ success: true });
  } catch (error) {
    console.error('更新计划提醒状态失败:', error);
    res.status(500).json({ success: false, message: '更新计划提醒状态失败' });
  }
});

module.exports = router; 